package com.imau.controller;

import com.alibaba.fastjson.JSON;
import com.imau.bean.User;
import com.imau.service.UserService;
import com.imau.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/user/*")
public class UserController extends BaseController{

    private UserService userService = new UserServiceImpl();
    /**18分
     * 用户登录
     * @param request
     * @param response
     * @throws IOException
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        BufferedReader br = request.getReader();
        String jsondata = br.readLine();
        //1.接收请求体数据,json串 3分
        User user = JSON.parseObject(jsondata,User.class);
        //2.将json串转换为java对象  3分
        User user1 = userService.getUser(user.getUserName());
        //3.调用service层方法  3分

        //判断用户名和密码是否正确
        if(user1!=null && user1.getPassword().equals(user.getPassword()))
        {
            //4. 获取session对象  3分
            HttpSession session = request.getSession();
            //5. 将用户名存到session中  3分
            session.setAttribute("username",user.getUserName());
            //6.响应结果OK 3分
            response.getWriter().write("OK");

        }else
        {
            //响应结果error
            response.getWriter().write("error");

        }


    }
}
